import 'dart:convert';

import 'package:city_pickers/city_pickers.dart';
import 'package:ecy_app_flutter/model/EcyLocationModel.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:keyboard_dismisser/keyboard_dismisser.dart';

import '../../../EcyRouter.dart';
import '../../../ecycommon/EcyCommonWidgets.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../ecycommon/utils/EcyUserUtil.dart';
import '../../../model/EcyApiCommonResponse.dart';
import '../model/EcyAdministrativeAreaModel.dart';
import '../model/EcyAdministrativeDivisionModel.dart';

class EcyAddressEditPage extends EcyCommonBaseWidget {
  late EcyLocationModel locationModel;

  EcyAddressEditPage({required super.key, required this.locationModel});

  @override
  _EcyAddressEditPageState createState() {
    return _EcyAddressEditPageState(this, this.locationModel);
  }
}

class _EcyAddressEditPageState extends EcyCommonBaseWidgetState {
  late EcyCommonBaseWidget controller;
  ScrollController scrollController = ScrollController();
  late EcyLocationModel locationModel;
  _EcyAddressEditPageState(
      EcyCommonBaseWidget vc, EcyLocationModel locationModelParam) {
    controller = vc;
    locationModel = locationModelParam;
  }

  final _formKey = GlobalKey<FormState>();
  final _consigneeController = TextEditingController();
  final _phoneController = TextEditingController();
  final _addressController = TextEditingController();
  final _addressDetailController = TextEditingController();
  var _switchFlag = false; // 开关状态-0关闭 1打开

  Map<String, String> provincesData = {};
  Map<String, dynamic> citiesData = {};

  Result _addressResult = Result(provinceId: '', cityId: '', areaId: '');

  @override
  void initState() {
    super.initState();
    if (locationModel != null && locationModel.id != null) {
      _consigneeController.text = locationModel.contact ?? '';
      _phoneController.text = locationModel.phone ?? '';
      _addressController.text =
          '${locationModel.provinceName ?? ''} ${locationModel.cityName ?? ''} ${locationModel.areaName ?? ''}';
      _addressDetailController.text = locationModel.detail ?? '';

      _switchFlag = locationModel.addressDefault == 1;
      _addressResult.provinceId = locationModel.provinceId;
      _addressResult.cityId = locationModel.cityId;
      _addressResult.areaId = locationModel.areaId;
    }
    requestData();
  }

  @override
  void dispose() {
    // 清理控制器，避免内存泄漏
    super.dispose();
    scrollController.dispose();
    _consigneeController.dispose();
    _phoneController.dispose();
    _addressDetailController.dispose();
  }

  @override
  Future<void> requestData({int pageIndex = 1, int type = 0}) async {
    super.requestData();
    var response = await EcyRequestbasemanager()
        .get("/app/api/app/commons/administrative/divisions", {});
    if (response != null) {
      var _respModel =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (_respModel.code == 0 || _respModel.code == 200) {
        EcyAdministrativeAreaModel _administrativeAreaModel =
            EcyAdministrativeAreaModel.fromJson(response["data"]);
        var _provinces = _administrativeAreaModel.provinces
            .map((e) => EcyAdministrativeDivisionModel.fromJson(e))
            .toList();
        var _cities = _administrativeAreaModel.cities
            .map((e) => EcyAdministrativeDivisionModel.fromJson(e))
            .toList();
        var _areas = _administrativeAreaModel.areas
            .map((e) => EcyAdministrativeDivisionModel.fromJson(e))
            .toList();

        Map<String, String> provincesMap = {};
        for (var areaModal in _provinces) {
          provincesMap[areaModal.id] = areaModal.name;
        }
        ;
        setState(() {
          provincesData = provincesMap;

          provincesData.forEach((key, value) {
            Map<String, dynamic> cityMap = {};
            for (var cityModel in _cities.where((e) => e.pid == key)) {
              cityMap[cityModel.id] = {"name": cityModel.name};

              Map<String, dynamic> areaMap = {};
              for (var areaModel
                  in _areas.where((area) => area.pid == cityModel.id)) {
                areaMap[areaModel.id] = {"name": areaModel.name};
              }
              citiesData[cityModel.id] = areaMap;
            }
            ;
            citiesData[key] = cityMap;
          });
        });
      }
    }
  }

  Future<void> _showCityPicker() async {
    Result? result = await CityPickers.showCityPicker(
      context: context,
      provincesData: provincesData,
      citiesData: citiesData,
      locationCode: locationModel.areaId ?? '110000000000',
      theme: Theme.of(context).copyWith(scaffoldBackgroundColor: Colors.white),
    );

    if (result != null) {
      // 使用选择的result
      // city 就是 result.city
      _addressResult = result;
      _addressController.text =
          '${result.provinceName} ${result.cityName} ${result.areaName}';
    }
  }

  Future<bool> _save() async {
    if (_consigneeController.text?.isEmpty ?? true) {
      EasyLoading.showToast("请输入收货人姓名", duration: const Duration(seconds: 1));
      return false;
    }
    if (_phoneController.text.length != 11) {
      EasyLoading.showToast("请输入正确的手机号", duration: const Duration(seconds: 1));
      return false;
    }
    if (_addressController.text?.isEmpty ?? true) {
      EasyLoading.showToast("请选择省市区", duration: const Duration(seconds: 1));
      return false;
    }
    if (_addressDetailController.text?.isEmpty ?? true) {
      EasyLoading.showToast("请输入详细地址", duration: const Duration(seconds: 1));
      return false;
    }
    Map<String, dynamic> body = {
      "id": locationModel?.id,
      "contact": _consigneeController.text,
      "phone": _phoneController.text,
      "address": _addressController.text,
      "detail": _addressDetailController.text,
      "addressDefault": _switchFlag ? 1 : 0,
      "province": _addressResult.provinceId,
      "city": _addressResult.cityId,
      "area": _addressResult.areaId,
      'street': _addressResult.areaId,
    };
    try {
      Map<String, dynamic> response;
      if (locationModel?.id != null) {
        response = await EcyRequestbasemanager()
            .put('/app/api/app/user/address/${locationModel?.id}', body);
      } else {
        response =
            await EcyRequestbasemanager().post("/app/api/app/user/address", body);
      }
      if (response != null) {
        var respModel =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (respModel.code == 0 || respModel.code == 200) {
          return true;
        } else {
          EasyLoading.showToast(respModel.msg ?? "请稍后再试", duration: const Duration(seconds: 1));
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 1));
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        child: KeyboardDismisser(
            gestures: const [
              GestureType.onTap,
              GestureType.onPanUpdateDownDirection
            ],
            child: Scaffold(
                resizeToAvoidBottomInset: true,
                backgroundColor: Colors.white,
                appBar: AppBar(
                  //导航栏
                  leadingWidth: 50.w,
                  leading: GestureDetector(
                    behavior: HitTestBehavior.translucent,
                    onTap: () {
                      EcyRouter.pop(context, "");
                    },
                    child: Align(
                      alignment: Alignment.centerRight,
                      child: Image.asset(
                        "assets/images/ic_back.png",
                        width: 30.w,
                      ),
                    ),
                  ),
                  titleSpacing: 0,
                  title: Text(locationModel?.id != null ? '编辑收货地址' : '新增收货地址',
                      style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w700,
                        fontSize: 16.sp,
                        color: const Color(0xFF000000),
                      )),
                  centerTitle: true,
                  backgroundColor: Colors.white,
                ),
                body: SingleChildScrollView(
                  controller: scrollController,
                  child: Padding(
                    padding: const EdgeInsets.all(8),
                    child: Column(
                      children: [
                        SizedBox(
                            width: MediaQuery.of(context).size.width,
                            child: Card(
                              color: Colors.white,
                              child: Form(
                                  key: _formKey,
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Padding(
                                        padding: const EdgeInsets.only(
                                            top: 8, bottom: 8),
                                        child: Container(
                                          width: double.infinity,
                                          color: const Color(0xFFFFFFFF),
                                          child: Column(
                                            children: [
                                              Row(
                                                mainAxisAlignment:
                                                    MainAxisAlignment.start,
                                                children: [
                                                  Expanded(
                                                    flex: 1,
                                                    child: Padding(
                                                        padding:
                                                            const EdgeInsets
                                                                .only(left: 15),
                                                        child: Text(
                                                          '收货人',
                                                          style: TextStyle(
                                                            fontFamily:
                                                                "PingFang SC",
                                                            fontWeight:
                                                                FontWeight.w700,
                                                            fontSize: 16.sp,
                                                            color: const Color(
                                                                0xFF262626),
                                                          ),
                                                        )),
                                                  ),
                                                  Expanded(
                                                    flex: 3,
                                                    child: Padding(
                                                      padding:
                                                          const EdgeInsets.only(
                                                              left: 10),
                                                      child: TextFormField(
                                                        controller:
                                                            _consigneeController,
                                                        decoration:
                                                            InputDecoration(
                                                          hintText: '请输入收货人姓名',
                                                          border:
                                                              InputBorder.none,
                                                          counterText: '',
                                                          hintStyle: TextStyle(
                                                            fontFamily:
                                                                "PingFang SC",
                                                            fontWeight:
                                                                FontWeight.w500,
                                                            fontSize: 16.sp,
                                                            color: const Color(
                                                                0xFF8C8C8C),
                                                          ),
                                                        ),
                                                        maxLength: 20,
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                              const Divider(
                                                  height: 0,
                                                  color: Color(0XFFF5F5F5)),
                                              Container(
                                                width: double.infinity,
                                                color: const Color(0xFFFFFFFF),
                                                padding: const EdgeInsets.only(
                                                    top: 5, bottom: 5),
                                                child: Row(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.start,
                                                  children: [
                                                    Expanded(
                                                      flex: 1,
                                                      child: Padding(
                                                          padding:
                                                              const EdgeInsets
                                                                  .only(
                                                                  left: 15),
                                                          child: Text(
                                                            '手机号',
                                                            style: TextStyle(
                                                              fontFamily:
                                                                  "PingFang SC",
                                                              fontWeight:
                                                                  FontWeight
                                                                      .w700,
                                                              fontSize: 16.sp,
                                                              color: const Color(
                                                                  0xFF262626),
                                                            ),
                                                          )),
                                                    ),
                                                    Expanded(
                                                      flex: 3,
                                                      child: Padding(
                                                        padding:
                                                            const EdgeInsets
                                                                .only(left: 10),
                                                        child: TextFormField(
                                                          controller:
                                                              _phoneController,
                                                          inputFormatters: [
                                                            FilteringTextInputFormatter
                                                                .digitsOnly,
                                                            LengthLimitingTextInputFormatter(
                                                                11)
                                                          ],
                                                          decoration:
                                                              InputDecoration(
                                                            hintText:
                                                                '请输入正确手机号',
                                                            border: InputBorder
                                                                .none,
                                                            hintStyle:
                                                                TextStyle(
                                                              fontFamily:
                                                                  "PingFang SC",
                                                              fontWeight:
                                                                  FontWeight
                                                                      .w500,
                                                              fontSize: 16.sp,
                                                              color: const Color(
                                                                  0xFF8C8C8C),
                                                            ),
                                                            counterText: '',
                                                          ),
                                                          maxLength: 20,
                                                        ),
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              const Divider(
                                                  height: 0,
                                                  color: Color(0XFFF5F5F5)),
                                              Container(
                                                width: double.infinity,
                                                color: const Color(0xFFFFFFFF),
                                                padding: const EdgeInsets.only(
                                                    top: 5, bottom: 5),
                                                child: Row(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.start,
                                                  children: [
                                                    Expanded(
                                                      flex: 1,
                                                      child: Padding(
                                                          padding:
                                                              const EdgeInsets
                                                                  .only(
                                                                  left: 15),
                                                          child: Text(
                                                            '所在地址',
                                                            style: TextStyle(
                                                              fontFamily:
                                                                  "PingFang SC",
                                                              fontWeight:
                                                                  FontWeight
                                                                      .w700,
                                                              fontSize: 16.sp,
                                                              color: const Color(
                                                                  0xFF262626),
                                                            ),
                                                          )),
                                                    ),
                                                    Expanded(
                                                        flex: 3,
                                                        child: Padding(
                                                          padding:
                                                              const EdgeInsets
                                                                  .only(
                                                                  left: 10),
                                                          child: TextFormField(
                                                              controller:
                                                                  _addressController,
                                                              readOnly: true,
                                                              decoration:
                                                                  InputDecoration(
                                                                hintText:
                                                                    '请选择省、市、区',
                                                                border:
                                                                    InputBorder
                                                                        .none,
                                                                hintStyle:
                                                                    TextStyle(
                                                                  fontFamily:
                                                                      "PingFang SC",
                                                                  fontWeight:
                                                                      FontWeight
                                                                          .w500,
                                                                  fontSize:
                                                                      16.sp,
                                                                  color: const Color(
                                                                      0xFF8C8C8C),
                                                                ),
                                                                counterText: '',
                                                              ),
                                                              maxLength: 30,
                                                              onTap: () {
                                                                _showCityPicker();
                                                              }),
                                                        )),
                                                  ],
                                                ),
                                              ),
                                              const Divider(
                                                  height: 0,
                                                  color: Color(0XFFF5F5F5)),
                                              Container(
                                                width: double.infinity,
                                                color: const Color(0xFFFFFFFF),
                                                padding: const EdgeInsets.only(
                                                    top: 5, bottom: 5),
                                                child: Row(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.start,
                                                  children: [
                                                    Expanded(
                                                      flex: 1,
                                                      child: Padding(
                                                          padding:
                                                              const EdgeInsets
                                                                  .only(
                                                                  left: 15),
                                                          child: Text(
                                                            '详细地址',
                                                            style: TextStyle(
                                                              fontFamily:
                                                                  "PingFang SC",
                                                              fontWeight:
                                                                  FontWeight
                                                                      .w700,
                                                              fontSize: 16.sp,
                                                              color: const Color(
                                                                  0xFF262626),
                                                            ),
                                                          )),
                                                    ),
                                                    Expanded(
                                                      flex: 3,
                                                      child: Padding(
                                                        padding:
                                                            const EdgeInsets
                                                                .only(left: 10),
                                                        child: TextFormField(
                                                          controller:
                                                              _addressDetailController,
                                                          decoration:
                                                              InputDecoration(
                                                            hintText:
                                                                '请输入详细的地址，例如小区/单元楼层等',
                                                            border: InputBorder
                                                                .none,
                                                            hintStyle:
                                                                TextStyle(
                                                              fontFamily:
                                                                  "PingFang SC",
                                                              fontWeight:
                                                                  FontWeight
                                                                      .w500,
                                                              fontSize: 16.sp,
                                                              color: const Color(
                                                                  0xFF8C8C8C),
                                                            ),
                                                            counterText: '',
                                                          ),
                                                          maxLength: 30,
                                                          maxLines: 2,
                                                        ),
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              const Divider(
                                                  height: 0,
                                                  color: Color(0XFFF5F5F5)),
                                              Container(
                                                width: double.infinity,
                                                color: const Color(0xFFFFFFFF),
                                                padding: const EdgeInsets.only(
                                                    top: 5, bottom: 5),
                                                child: Row(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment
                                                          .spaceBetween,
                                                  children: [
                                                    Padding(
                                                        padding:
                                                            const EdgeInsets
                                                                .only(left: 15),
                                                        child: Text(
                                                          '设置默认地址',
                                                          style: TextStyle(
                                                            fontFamily:
                                                                "PingFang SC",
                                                            fontWeight:
                                                                FontWeight.w700,
                                                            fontSize: 16.sp,
                                                            color: const Color(
                                                                0xFF262626),
                                                          ),
                                                        )),
                                                    Transform.scale(
                                                      scale: 0.8,
                                                      child: CupertinoSwitch(
                                                        value: _switchFlag,
                                                        onChanged: (value) {
                                                          setState(() {
                                                            _switchFlag = value;
                                                          });
                                                        },
                                                        activeColor:
                                                            Color(0xFFEA4B9B),
                                                      ),
                                                    )
                                                  ],
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),
                                    ],
                                  )),
                            )),
                        const Padding(padding: EdgeInsets.only(bottom: 100)),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children: [
                            Expanded(
                              flex: 1,
                              child: SizedBox(
                                height: 50.h,
                                child: TextButton(
                                    onPressed: () async {
                                      bool isSuccess = await _save();
                                      if (isSuccess) {
                                        Navigator.pop(context, true);
                                      }
                                    },
                                    style: const ButtonStyle(
                                      alignment: Alignment.center,
                                      backgroundColor: WidgetStatePropertyAll(
                                          Color(0xFFEA4B9B)),
                                      foregroundColor:
                                          WidgetStatePropertyAll(Colors.white),
                                    ),
                                    child: const Text(
                                      '保存',
                                      style: TextStyle(
                                        height: 1,
                                        fontSize: 18,
                                        leadingDistribution:
                                            TextLeadingDistribution
                                                .even, // 设置leading策略
                                      ),
                                    )),
                              ),
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                ))));
  }
}
